package fwk.form.tabManager
	
	
	import flash.display.InteractiveObject
	import flash.display.DisplayObjectContainer
	import flash.events.KeyboardEvent;
	import flash.events.FocusEvent;
	
	
	public class TabManager{
		
		
		private var _tab:Array;
		private var _index:int;
		private var _containerGlobal:DisplayObjectContainer;
		
		private var _actif:Boolean;
		
		public function TabManager(containerGlobal:DisplayObjectContainer) {
			
			_containerGlobal = containerGlobal;
			_tab = new Array();
			_index = -1;
			_actif = false;
			

		}
		
		public function add(clip:InteractiveObject):void {
			_tab.push(clip);
		}
		
		public function select(clip:InteractiveObject) {
			
			_index = getIndex(clip);
			_select(_tab[_index]);
		}
		
		public function kill():void
		{
			if (_actif) {
				_containerGlobal.stage.stageFocusRect = true;
				_containerGlobal.stage.tabChildren = true;
				_containerGlobal.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
				
				for (var i:int = 0; i < _tab.length; i++) {
					_tab[i].removeEventListener(FocusEvent.FOCUS_IN, _onFocusIn) ;
				}

				_actif = false;
				_tab = new Array();
			}
			
		}
		public function init():void
		{
			if (!_actif) {
				//_containerGlobal.stage.stageFocusRect = false;
				_containerGlobal.stage.tabChildren = false;
				_containerGlobal.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
				
				for (var i:int = 0; i < _tab.length; i++) {
					_tab[i].addEventListener(FocusEvent.FOCUS_IN, _onFocusIn) ;
				}
				
				_actif = true;
			}
			
		}
		private function _onFocusIn(e:FocusEvent)
		{
			trace("_onFocusIn " + e.currentTarget);
			_index = getIndex(e.currentTarget as InteractiveObject);
		}
		private function _select(clip:InteractiveObject) {
			
			_containerGlobal.stage.focus = clip;
		}
		private function keyPressHandler(e:KeyboardEvent) {
			
			trace("keyPressHandler" );
			
			if (e.keyCode == 9) { 
				_index++;
				if (_index == _tab.length) _index = 0;
				trace(" ---- Tabulation " + _index + " focus in " + _tab[_index]);
				_select(_tab[_index]);
			} 
		}
		
		private function getIndex(clip:InteractiveObject):int {
			
			for (var i:int = 0; i < _tab.length; i++) {
				if (_tab[i] == clip) {
					
					_index = i;
					return _index;
				}
			}
			
			return -1;
		}
		

	}
	
}